package com.tanhua.dubbo.api;

import com.tanhua.model.db.Friend;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * @auther : 白月尘
 * @date : 18:43  2021/10/23
 */
@DubboService
public class FriendApiImpl implements FriendApi {
    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public void save(long userId, long friendId) {
        Criteria criteria = Criteria.where("userId").is(userId).and("friendId").is(friendId);
        if (!mongoTemplate.exists(Query.query(criteria), Friend.class)) {
            Friend friend1 = new Friend();
            friend1.setCreated(System.currentTimeMillis());
            friend1.setUserId(userId);
            friend1.setFriendId(friendId);
            mongoTemplate.save(friend1);
        }
        Criteria criteria1 = Criteria.where("userId").is(friendId).and("friendId").is(userId);
        boolean exists = mongoTemplate.exists(Query.query(criteria1), Friend.class);
        if (!exists) {
            Friend friend2 = new Friend();
            friend2.setCreated(System.currentTimeMillis());
            friend2.setUserId(friendId);
            friend2.setFriendId(userId);
            mongoTemplate.save(friend2);
        }
    }

    @Override
    public List<Friend> findFriends(Integer page, Integer pageSize, long userId) {
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = Query.query(criteria).skip((page - 1) * pageSize).limit(pageSize);
        return mongoTemplate.find(query,Friend.class);
    }


    @Override
    public void delete(Long userId, Long friendId) {
        Criteria criteria = Criteria.where("userId").is(userId)
                .and("friendId").is(friendId);
        mongoTemplate.remove(Query.query(criteria),Friend.class);
        Criteria criteria1 = Criteria.where("userId").is(friendId)
                .and("friendId").is(userId);
        mongoTemplate.remove(Query.query(criteria1),Friend.class);

    }

}
